<template>
    <div>
        <!-- 表头分页查询条件， shadow="never" 指定 card 卡片组件没有阴影 -->
        <el-card shadow="never" class="mb-5">
            <!-- flex 布局，内容垂直居中 -->
            <div class="flex items-center">
                <el-text>知识库标题</el-text>
                <div class="ml-3 w-52 mr-5"><el-input v-model="searchWikiTitle" placeholder="请输入（模糊查询）" clearable />
                </div>

                <el-text>创建日期</el-text>
                <div class="ml-3 w-30 mr-5">
                    <!-- 日期选择组件（区间选择） -->
                    <el-date-picker v-model="pickDate" type="daterange" range-separator="至" start-placeholder="开始时间"
                        end-placeholder="结束时间" size="default" :shortcuts="shortcuts" @change="datepickerChange" />
                </div>

                <el-button type="primary" class="ml-3" :icon="Search" @click="getWikiPageListData">查询</el-button>
                <el-button class="ml-3" :icon="RefreshRight" @click="reset">重置</el-button>
            </div>
        </el-card>

        <el-card shadow="never">
            <!-- 新增知识库按钮 -->
            <div class="mb-5">
                <el-button type="primary" @click="addWikiBtnClick">
                    <el-icon class="mr-1">
                        <Plus />
                    </el-icon>
                    新增知识库</el-button>
            </div>

            <!-- 分页列表 -->
            <el-table :data="tableData" border stripe v-loading="tableLoading" table-layout="auto">
                <el-table-column type="index" label="序号" width="60" />
                <el-table-column prop="id" label="知识库ID" />
                <el-table-column prop="title" label="标题" />
                <el-table-column prop="cover" label="封面">
                    <template #default="scope">
                        <el-image style="width: 100px;" :src="scope.row.cover" />
                    </template>
                </el-table-column>
                <el-table-column prop="isTop" label="是否置顶">
                    <template #default="scope">
                        <el-switch v-model="scope.row.isTop" inline-prompt :active-icon="Check"
                            @change="handleIsTopChange(scope.row)" :inactive-icon="Close" />
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="发布时间" />
                <el-table-column prop="isPublish" label="是否发布">
                    <template #default="scope">
                        <el-switch v-model="scope.row.isPublish" inline-prompt :active-icon="Check"
                            @change="handleIsPublishChange(scope.row)" :inactive-icon="Close" />
                    </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="160">
                    <template #default="scope">
                        <el-tooltip class="box-item" effect="dark" content="编辑" placement="bottom">
                            <el-button size="small" @click="showEditWikiDialog(scope.row)" :icon="Edit" circle>
                            </el-button>
                        </el-tooltip>

                        <el-tooltip class="box-item" effect="dark" content="编辑目录" placement="bottom">
                            <el-button size="small" @click="showEditWikiCatalogDialog(scope.row)" :icon="Tickets"
                                circle>
                            </el-button>
                        </el-tooltip>

                        <el-tooltip class="box-item" effect="dark" content="预览" placement="bottom">
                            <el-button size="small" :icon="View" circle>
                            </el-button>
                        </el-tooltip>

                        <el-tooltip class="box-item" effect="dark" content="删除" placement="bottom">
                            <el-button type="danger" size="small" :icon="Delete" circle
                                @click="deleteWikiData(scope.row)">
                            </el-button>
                        </el-tooltip>

                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="mt-10 flex justify-center">
                <el-pagination v-model:current-page="current" v-model:page-size="size" :page-sizes="[5, 10, 20, 50]"
                    :small="false" :background="true" layout="total, sizes, prev, pager, next, jumper" :total="total"
                    @size-change="handleSizeChange" @current-change="getWikiPageListData" />
            </div>

        </el-card>
        <!-- 新增知识库 -->
        <FormDialog ref="formDialogRef" title="新增知识库" destroyOnClose @submit="onSubmit">
            <el-form ref="formRef" :rules="rules" :model="form">
                <el-form-item label="标题" prop="title" label-width="80px" size="large">
                    <el-input v-model="form.title" placeholder="请输入知识库标题" maxlength="24" show-word-limit clearable />
                </el-form-item>
                <el-form-item label="封面" prop="cover" label-width="80px" size="large">
                    <el-upload class="avatar-uploader" action="#" :on-change="handleCoverChange" :auto-upload="false"
                        :show-file-list="false">
                        <img v-if="form.cover" :src="form.cover" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="摘要" prop="summary" label-width="80px" size="large">
                    <!-- :rows="3" 指定 textarea 默认显示 3 行 -->
                    <el-input v-model="form.summary" :rows="3" maxlength="128" show-word-limit type="textarea"
                        placeholder="请输入知识库摘要" clearable />
                </el-form-item>
            </el-form>
        </FormDialog>
        <!-- 编辑知识库 -->
        <FormDialog ref="editFormDialogRef" title="编辑知识库" destroyOnClose @submit="onEditWikiSubmit">
            <el-form ref="editFormRef" :rules="rules" :model="editForm">
                <el-form-item label="标题" prop="title" label-width="80px" size="large">
                    <el-input v-model="editForm.title" placeholder="请输入知识库标题" maxlength="20" show-word-limit
                        clearable />
                </el-form-item>
                <el-form-item label="封面" prop="cover" label-width="80px" size="large">
                    <el-upload class="avatar-uploader" action="#" :on-change="handleUpdateCoverChange"
                        :auto-upload="false" :show-file-list="false">
                        <img v-if="editForm.cover" :src="editForm.cover" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="摘要" prop="summary" label-width="80px" size="large">
                    <!-- :rows="3" 指定 textarea 默认显示 3 行 -->
                    <el-input v-model="editForm.summary" :rows="3" maxlength="30" show-word-limit type="textarea"
                        placeholder="请输入知识库摘要" clearable />
                </el-form-item>
            </el-form>
        </FormDialog>
        <!-- 目录编辑 -->
        <WikiCatalogEditDialog ref="editCatalogFormDialogRef" title="编辑目录" width="70%" destroyOnClose>

        </WikiCatalogEditDialog>
    </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { Search, RefreshRight, Check, Close, Delete, Edit, Tickets, View } from '@element-plus/icons-vue'
import moment from 'moment'
import { addWiki, deleteWiki, getWikiPageList, updatePublishStatus, updateTopStatus, updateWiki } from '@/api/admin/wiki';
import { showMessage, showModel } from '@/composables/utils';
import FormDialog from '@/components/FormDialog.vue'
import WikiCatalogEditDialog from '@/components/WikiCatalogEditDialog.vue';
import { uploadFile } from '@/api/admin/file';
// 模糊搜索的知识库标题
const searchWikiTitle = ref('')
// 日期
const pickDate = ref('')

// 查询条件：开始结束时间
const startDate = reactive({})
const endDate = reactive({})

// 监听日期组件改变事件，并将开始结束时间设置到变量中
const datepickerChange = (e) => {
    startDate.value = moment(e[0]).format('YYYY-MM-DD')
    endDate.value = moment(e[1]).format('YYYY-MM-DD')

    console.log('开始时间：' + startDate.value + ', 结束时间：' + endDate.value)
}

//近期时间
const shortcuts = [
    {
        text: '最近一天',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 1000 * 3600 * 24 * 1)
            return [start, end]
        }
    },
    {
        text: '最近三天',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 1000 * 3600 * 24 * 3)
            return [start, end]
        }
    },
    {
        text: '最近一周',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 1000 * 3600 * 24 * 7)
            return [start, end]
        }
    },
    {
        text: '最近一个月',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 1000 * 3600 * 24 * 30)
            return [start, end]
        }
    },
    {
        text: '最近三个月',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 1000 * 3600 * 24 * 90)
            return [start, end]
        }
    },
    {
        text: '最近六个月',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 1000 * 3600 * 24 * 180)
            return [start, end]
        }
    },
    {
        text: '最近一年',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 1000 * 3600 * 24 * 365)
            return [start, end]
        }
    }
]

// 重置
const reset = () => {
    pickDate.value = ''
    startDate.value = null
    endDate.value = null
    searchWikiTitle.value = ''
}

// 知识库列表
const tableData = ref([])
// 当前页码
const current = ref(0)
// 每一页的数据量
const size = ref(10)
// 总数据量
const total = ref(0)
//表格数据加载动画
const tableLoading = ref(false)
// 获取知识库分页列表数据
const getWikiPageListData = () => {
    // 显示表格加载数据动画
    tableLoading.value = true
    // 构造请求参数
    let params = {
        "current": current.value,
        "size" : size.value,
        "title": searchWikiTitle.value,
        "startDate": startDate.value,
        "endDate": endDate.value
    }

    // 发送请求
    getWikiPageList(params).then((res) => {
        if (res.success == true) {
            // 获取知识库分页数据成功
            tableData.value = res.data
            current.value = res.pageIndex
            size.value = res.size
            total.value = res.total
            // showMessage("获取知识库列表成功！")
        } else {
            showMessage(res.message, "error")
        }
    }).finally(() => {tableLoading.value = false})
}
getWikiPageListData()

// 每页展示数量变更事件
const handleSizeChange = (chooseSize) => {
    console.log('选择的页码' + chooseSize)
    size.value = chooseSize
    getWikiPageListData()
}
// 新增知识库对话框
const formDialogRef = ref(null)
// 编辑知识库对话框
const editFormDialogRef = ref(null)
// 编辑知识库目录对话框
const editCatalogFormDialogRef = ref(null)
// 表单引用
const formRef = ref(null)
const editFormRef = ref(null)
const form = ref({
    "cover": "",
    "summary": "",
    "title": ""
})
// 编辑表单引用
const editForm = ref({
    "id": 0,
    "cover": "",
    "summary": "",
    "title": ""
})
// 新增知识库按钮点击事件
const addWikiBtnClick = () => {
    formDialogRef.value.open()
}
// 编辑知识库按钮点击事件
const showEditWikiDialog = (row) => {
    editFormDialogRef.value.open()
    // 获取知识库相关信息
    editForm.value.title = row.title
    editForm.value.cover = row.cover
    editForm.value.summary = row.summary
    editForm.value.id = row.id
}
// 编辑目录按钮点击事件
const showEditWikiCatalogDialog = (row) => {
    // 显示编辑目录对话框, 并传入知识库 ID
    editCatalogFormDialogRef.value.open(row.id)
}

const rules = {
    "title": [
        {
            required: true,
            message: "知识库标题名称不允许为空！",
            trigger: "blur"
        },
        {
            min: 1,
            max: 24,
            message: '知识库名称字数要求大于 1 个字符，小于 24 个字符',
            trigger: 'blur'
        }
    ],
    "summary": [
        {
            required: true,
            message: "知识库介绍（摘要）不允许为空！",
            trigger: "blur"
        },
        {
            min: 1,
            max: 128,
            message: '分类名称字数要求大于 1 个字符，小于 128 个字符',
            trigger: 'blur'
        }
    ],
    "cover": [
        {
            required: true,
            message: "知识库封面不允许为空！",
            trigger: "blur"
        }
    ] 
}

// 上传封面图片
const handleCoverChange = (file) => {
    // 表单对象
    let formData = new FormData()
    // 添加file字段，并将文件传入
    formData.append("file", file.raw)
    uploadFile(formData).then((res) => {
        if (res.success == false) {
            // 上传失败
            showMessage(res.message, "error")
            return
        } else {
            //成功则设置表单中的封面链接，并提示封面上传成功
            form.value.cover = res.data.url
            showMessage("上传成功！")
        }
    })
}

// 更新上传封面图片
const handleUpdateCoverChange = (file) => {
    // 表单对象
    let formData = new FormData()
    // 添加file字段，并将文件传入
    formData.append("file", file.raw)
    uploadFile(formData).then((res) => {
        if (res.success == false) {
            // 上传失败
            showMessage(res.message, "error")
            return
        } else {
            //成功则设置表单中的封面链接，并提示封面上传成功
            editForm.value.cover = res.data.url
            showMessage("上传成功！")
        }
    })
}

// 提交表单内容
const onSubmit = () => {
    // 验证表单字段
    formRef.value.validate((valid) => {
        if (!valid) {
            console.log("表单验证不通过！")
            return false
        }
        // 显示提交按钮
        formDialogRef.value.showBtnLoading()
        addWiki(form.value).then((res) => {
            if (res.success == true) {
                showMessage("添加知识库成功！", "success")
                // 将所提交表单的数据置空
                form.value.title = ""
                form.value.cover = ""
                form.value.summary = ""
                // 隐藏对话框
                formDialogRef.value.close()
                // 重新请求分页接口
                getWikiPageListData()
            } else {
                showMessage(res.message, "error")
            }
        }).finally(() => {formDialogRef.value.closeBtnLoading()})
    })
}

// 提交编辑表单内容
const onEditWikiSubmit = () => {
    // 验证表单字段
    editFormRef.value.validate((valid) => {
        if (!valid) {
            console.log("表单验证不通过！")
            return false
        }
        // 显示提交按钮
        editFormDialogRef.value.showBtnLoading()
        // 修改知识库信息
        updateWiki(editForm.value).then((res) => {
            if (res.success == true) {
                showMessage("修改知识库成功！")
                // 将所提交表单的数据置空
                editForm.value.title = ""
                editForm.value.cover = ""
                editForm.value.summary = ""
                editForm.value.id = null
                // 隐藏对话框
                editFormDialogRef.value.close()
                // 重新请求分页接口
                getWikiPageListData()
            } else {
                showMessage(res.message, "error")
            }
        }).finally(() => {editFormDialogRef.value.closeBtnLoading()})
    })
}

// 获取知识库相关信息
const getWikiInfo = (id) => {
    // 构造请求参数
    let params = {
        "id": id
    }
    // 发送请求
    getWikiInfo(params).then((res) => {
        if (res.success == true) {
            // 获取知识库信息成功
            editForm.value.title = res.data.title
            editForm.value.cover = res.data.cover
            editForm.value.summary = res.data.summary
        } else {
            showMessage(res.message, "error")
        }
    })
}

// 删除知识库
const deleteWikiData = (row) => {
    showModel("是否确认删除知识库：" + row.title + "？", "warning", "知识库数据删除提示").then(() => {
        let params = {
            "id": row.id
        }
        // 发送删除知识库请求
        deleteWiki(params).then((res) => {
            if (res.success == true) {
                // 删除数据库成功
                showMessage("删除知识库：" + row.title + "成功！")
                // 重新获取分页数据
                getWikiPageListData()
            } else {
                showMessage(res.message, "error")
            }
        })
    }).catch(() => {
        showMessage("已取消删除知识库：" + row.title + "!", "warning")
    })
}
// 更改知识库置顶状态
const handleIsTopChange = (row) => {
    // 构造请求参数
    let params = {
        "id": row.id,
        "isTop": row.isTop
    }
    // 发送请求
    updateTopStatus(params).then((res) => {
        // 重新获取分页接口，渲染列表数据
        getWikiPageListData()
        if (res.success == true) {
            showMessage(row.isTop ? "置顶成功！" : "已取消置顶！")
        } else {
            showMessage(res.message, "error")
        }
    })
}

// 更改知识库发布状态
const handleIsPublishChange = (row) => {
    // 构造请求参数
    let params = {
        "id": row.id,
        "isPublish": row.isPublish
    }
    // 发送请求
    updatePublishStatus(params).then((res) => {
        //  重新获取分页接口
        getWikiPageListData()
        if (res.success == true) {
            showMessage(row.isPublish ? "发布成功！" : "已取消发布！")
        } else {
            showMessage(res.message, "error")
        }
    })
}

</script>

<style scoped>
        /* 封面图片样式 */
        .avatar-uploader .avatar {
            width: 200px;
            height: 100px;
            display: block;
        }
    
        .el-icon.avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 200px;
            height: 100px;
            text-align: center;
        }
</style>
